package com.mbl.base.config.security;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 权限拦截器
 */
@Component("rbacService")
public class RbacServiceImpl implements RbacService {
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 临时放行所有权限
     */
    private boolean istemp = true;

    private List<String> unCheckUrls = new ArrayList<>();
    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        final String requestURI = request.getRequestURI();

        if(istemp){
            return true;
        }

        // 开放权限资源
        for (int i = 0; i < unCheckUrls.size(); i++) {
            if(antPathMatcher.match(unCheckUrls.get(i), requestURI)){
                return true;
            }
        }
        Object principal = authentication.getPrincipal();
        boolean hasPermission = false;
        if (principal instanceof UserDetails) { //首先判断先当前用户是否是我们UserDetails对象。
            String userName = ((UserDetails) principal).getUsername();
            Set<String> urls = new HashSet<>(); // 数据库读取 //读取用户所拥有权限的所有URL
            urls.add("/whoim");
            urls.add("/");
            // 注意这里不能用equal来判断，因为有些URL是有参数的，所以要用AntPathMatcher来比较
            for (String url : urls) {
                if (antPathMatcher.match(url, requestURI)) {
                    hasPermission = true;
                    break;
                }
            }
        }
        return hasPermission;
    }

    RbacServiceImpl(){
        unCheckUrls.add("/webjars");
    }


}
